package com.dosgi.kit;

import java.math.BigDecimal;

/**
 * 值处理工具类
 * 
 * @author dingnate
 *
 */
public class ValueKit {
	public final static String EMPTY = "";
	public final static Byte b = new Byte((byte) 0);
	public final static Short s = new Short((short) 0);
	public final static Integer i = new Integer(0);
	public final static Long l = new Long(0L);
	public final static Float f = new Float(0f);
	public final static Double d = new Double(0d);
	public final static BigDecimal bd = new BigDecimal(0);

	ValueKit() {
	}

	/**
	 * @param value
	 * @param defaultValue
	 * @return
	 */
	public static <T> T getValue(T value, T defaultValue) {
		if (value == null){
			return defaultValue;
		}
		if (value instanceof String){
			return EMPTY.equals(value) ? defaultValue : value;
		}
		if (!(value instanceof Number)){
			return value;
		}
		if (value instanceof Byte){
			return b.equals(value) ? defaultValue : value;
		}
		if (value instanceof Short){
			return s.equals(value) ? defaultValue : value;
		}
		if (value instanceof Integer){
			return i.equals(value) ? defaultValue : value;
		}
		if (value instanceof Long){
			return l.equals(value) ? defaultValue : value;
		}
		if (value instanceof Float){
			return f.equals(value) ? defaultValue : value;
		}
		if (value instanceof Double){
			return d.equals(value) ? defaultValue : value;
		}
		if (value instanceof BigDecimal){
			return bd.equals(value) ? defaultValue : value;
		}
		return bd.equals(new BigDecimal(value.toString())) ? defaultValue : value;
	}

	public static final Object convert(String s, Class<?> type) {
		if (type == String.class){
			return s;
		}
		if (type == Integer.class || type == int.class){
			return Integer.valueOf(s);
		}
		if (type == Long.class || type == long.class){
			return Long.valueOf(s);
		}
		if (type == Double.class || type == double.class){
			return Double.valueOf(s);
		}
		if (type == Float.class || type == float.class){
			return Float.valueOf(s);
		}
		if (type == Boolean.class || type == boolean.class) {
			String value = s.toLowerCase();
			if ("1".equals(value) || "true".equals(value)) {
				return Boolean.TRUE;
			} else if ("0".equals(value) || "false".equals(value)) {
				return Boolean.FALSE;
			} else {
				throw new RuntimeException("Can not parse to boolean type of value: " + s);
			}
		}
		if (type == java.math.BigDecimal.class){
			return new java.math.BigDecimal(s);
		}
		if (type == java.math.BigInteger.class){
			return new java.math.BigInteger(s);
		}
		if (type == byte[].class){
			return s.getBytes();
		}
		throw new RuntimeException(type.getName()
				+ " can not be converted, please use other type in your config class!");
	}
}
